package demo;

import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;

import java.lang.reflect.Method;

/**
 * Created by mo.fei on 2015/10/22.
 */
public class JavassistDemo2 {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        ProxyFactory factory=new ProxyFactory();
        //设置父类，ProxyFactory将会动态生成一个类，继承该父类
        factory.setSuperclass(BaseService.class);
        //设置过滤器，判断哪些方法调用需要被拦截
        factory.setFilter(new MethodFilter() {
            public boolean isHandled(Method method) {
                if (method.getName().startsWith("getName")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        //设置拦截处理
        factory.setHandler(new MethodHandler() {
            public Object invoke(Object o, Method method, Method method1, Object[] objects) throws Throwable {
                //拦截后前置处理，改写name属性的内容
                //实际情况可根据需求修改
                BaseService bs=(BaseService)o;
                bs.setName("mofei");
                return method1.invoke(o,objects);
            }
        });

        Class<?> c=factory.createClass();
        BaseService bs=(BaseService)c.newInstance();
        System.out.println(bs.getName());
    }
}
